package com.suda.sudaexamsystem.controller;

import com.suda.sudaexamsystem.dto.ClazzDto;
import com.suda.sudaexamsystem.dto.UserDto;
import com.suda.sudaexamsystem.pojo.Clazz;
import com.suda.sudaexamsystem.pojo.User;
import com.suda.sudaexamsystem.service.ClazzService;
import com.suda.sudaexamsystem.service.UserService;
import com.suda.sudaexamsystem.util.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/clazz")
@Slf4j
public class ClazzController {
    @Autowired
    private ClazzService clazzService;
    @Autowired
    private UserService userService;

    /**
     * 查询班级
     * {"msg":"操作成功","code":200,"data":{"id":1,"name":"神雕侠侣","owner":{"id":1,"name":"admin","login_name":"段智兴","sex":"男"}}}
     */
    @GetMapping(value = "/{clazzId}", produces = {"application/json;charset=UTF-8"})
    public AjaxResult findClazz(@PathVariable("clazzId") int clazzId) {
        Clazz clazz = clazzService.findById(clazzId);
        ClazzDto clazzDto = clazz.toDto();
        clazzDto.setOwner(clazz.getOwner().toDto());
        return AjaxResult.success(clazzDto);
    }

    /**
     * 查看班级人员
     * {"msg":"操作成功","code":200,"data":[{"id":1,"name":"admin","login_name":"段智兴","sex":"男"}]}
     */
    @GetMapping(value = "/getUsers/{clazzId}", produces = {"application/json;charset=UTF-8"})
    public AjaxResult getUsers(@PathVariable("clazzId") int clazzId) {
        List<User> userList = userService.findUsersForClazzId(clazzId);
        List<UserDto> userDtoList = new ArrayList<>();
        for (User user : userList) {
            userDtoList.add(user.toDto());
        }
        return AjaxResult.success(userDtoList);
    }

    // 解散班级
    @PostMapping(value = "/remove/{clazzId}", produces = {"application/json;charset=UTF-8"})
    public AjaxResult removeClazz(@PathVariable("clazzId") int clazzId) {
        log.info("班级id：" + clazzId);
        clazzService.deleteClazz(clazzId);
        return AjaxResult.success();
    }
}
